import { observable, action, runInAction, toJS } from "mobx";
import * as HumanBodyDatabaseManagementApi from "@/service/api/HumanBodyDatabaseManagementApi";

import { str_to_base64, base64_to_str, deep_copy } from "../../utils/utils";
import { message } from "antd";
let DeletePictureSuccessArray = [];
let DeleteHumanBodySuccessArray = [];
class HumanBodyManageStore {
  @observable createdFeatureLibrary = false;
  @observable noTaskRunning = true;

  @observable created_task = false//创建过视频上传任务

  @observable upload_video_ok = true//视频创建任务是否上传完毕了
  @action change_upload_video_ok = (condition) => {
    this.upload_video_ok = condition
  }

  @action change_created_task = (condition) => {
    this.created_task = condition
  }
  @action changeNoTaskRunning = (condition) => {
    this.noTaskRunning = condition
  }
  @action listAllFeatureLibrariesFun = async userName => {
    await HumanBodyDatabaseManagementApi.listAllFeatureLibrariesFun(userName).then(res => {
      console.log(res);

      for (let [index, item] of res.data.result.entries()) {
        console.log('创建的特征库为', item)
      }
      runInAction(() => {
        if (res.code === 200) {
          if (res.data.total > 0) {
            this.createdFeatureLibrary = true;
          } else {
            this.createdFeatureLibrary = false;
          }
        }
      });
    });
  };

  @action HumanBodyFeatureDatabaseCreationFun = async (userName, token) => {
    const formData = new FormData();
    formData.append("libid", userName);
    await HumanBodyDatabaseManagementApi.HumanBodyFeatureDatabaseCreationFun(formData, token).then(res => {
      console.log(res);
      if (res.code === 200) {
        console.log("创建成功默认人体库,特征库名称为" + res.data.fid);
      } else if (
        res.code === 500 &&
        res.exp.indexOf("UNIQUE constraint failed") > -1
      ) {
        console.log("人体库已存在,特征库名称为", userName);
      }
    });
  };
  @action UploadPicturesToExtractHumanFeaturesFun = async file => {
    let UploadPicturesOfHumanBodyFeatureExtraction = {};
    const formData = new FormData();
    formData.append("src", file);
    formData.append("croped", "0");
    const res = await HumanBodyDatabaseManagementApi.HumanFeatureExtractionFun(formData);
    console.log(res);
    if (res.code === 200) {
      if (res.data.length > 0) {
        UploadPicturesOfHumanBodyFeatureExtraction.condition = "success";
        let qualified_body_array = []
        for (let [index, item] of res.data.entries()) {
          if (item.h / item.w > 0.1 && item.h / item.w < 9 && item.w * item.h >= 100) {
            qualified_body_array.push(item)
          }
        }
        UploadPicturesOfHumanBodyFeatureExtraction.qualified_body_array = qualified_body_array
      } else {
        UploadPicturesOfHumanBodyFeatureExtraction.condition = "fail";
      }
    }

    return UploadPicturesOfHumanBodyFeatureExtraction;
  }



  @action HumanFeatureExtractionFun = async file => {
    let HumanFeatureExtractionCondition = {};
    const formData = new FormData();
    formData.append("src", file);
    formData.append("croped", "0");
    const res = await HumanBodyDatabaseManagementApi.HumanFeatureExtractionFun(formData);
    console.log(res);

    if (res.code === 200) {
      if (res.data.length > 0) {
        HumanFeatureExtractionCondition.condition = "success";
        let CurrentMaximumData = undefined//当前最大的数据
        for (let [index, item] of res.data.entries()) {
          if (index === 0) {
            CurrentMaximumData = item
          } else {
            CurrentMaximumData.w > item.w ? CurrentMaximumData : CurrentMaximumData = item
          }
        }
        HumanFeatureExtractionCondition.feature_vector = CurrentMaximumData.vec;
        HumanFeatureExtractionCondition.body_position = CurrentMaximumData
      } else {
        HumanFeatureExtractionCondition.condition = "fail";
      }
    }

    return HumanFeatureExtractionCondition;
  };
  @action HumanCharacterBankInsertFun = async (userName, token, file, feature_vector, UserId) => {
    let HumanCharacteristicsDatabaseInsertion = {};
    const formData = new FormData();
    let vecList = "base64://" + encodeURIComponent(feature_vector);
    formData.append("src", vecList);
    formData.append("uid", str_to_base64(file.name));
    formData.append("nick", str_to_base64(file.name));
    formData.append("img_src", UserId + str_to_base64(file.name));
    const res = await HumanBodyDatabaseManagementApi.HumanCharacterBankInsertFun(formData, userName, token);
    console.log(res);
    if (res.code === 200) {
      HumanCharacteristicsDatabaseInsertion.condition = "success";
      console.log("人体特征库插入成功");
    } else if (res.code === 422) {
      HumanCharacteristicsDatabaseInsertion.condition = "fail";
      HumanCharacteristicsDatabaseInsertion.fail_reason = "系统中已存在本图片处理记录";
      console.log("图片命名重复，请更换图片名");
    } else {
      HumanCharacteristicsDatabaseInsertion.condition = "fail";
      HumanCharacteristicsDatabaseInsertion.fail_reason = "插入失败";
      console.log("插入失败");
    }
    return HumanCharacteristicsDatabaseInsertion;
  };
  //列出特征库所有元素
  @action ListsAllElementsOfTheFeatureLibrary = async (userName, token) => {
    let AllElementsOfTheFeatureLibrary = [];
    await HumanBodyDatabaseManagementApi.ListsAllElementsOfTheFeatureLibrary(userName, token).then(res => {
      console.log(res);
      if (res.code === 200) {
        runInAction(() => {
          AllElementsOfTheFeatureLibrary = res.data.result;
        });
      }
    });
    return AllElementsOfTheFeatureLibrary;
  };
  //图片仓库上传函数
  @action PhotoWarehouseUploadFun = async (file, name, UserId) => {
    let PhotoGalleryInsertCase = {};
    const formData = new FormData();
    formData.append("src", file);
    formData.append("fid", UserId + str_to_base64(name));
    const res = await HumanBodyDatabaseManagementApi.PhotoWarehouseUploadFun(formData);
    console.log(res);
    if (res.code === 200) {
      PhotoGalleryInsertCase.condition = "success";
    } else if (res.code === 400) {
      PhotoGalleryInsertCase.condition = "fail";
      PhotoGalleryInsertCase.fail_reason = "图片库中已存在这个图片";
      console.log("图片库中已存在这个图片");
    } else {
      PhotoGalleryInsertCase.fail_reason = "图片上传失败";
      console.log("图片上传失败");
    }
    return PhotoGalleryInsertCase;
  };
  @action ImageWarehouseAcquisitionFun = userName => {
    HumanBodyDatabaseManagementApi.ImageWarehouseAcquisitionFun(userName).then(res => {
      console.log(res);
    });
  };

  @action HumanCharacterLibraryRemovesElements = async (ID, userName, token) => {
    await HumanBodyDatabaseManagementApi.HumanCharacterLibraryRemovesElements(ID, userName, token).then(res => {
      console.log(res);
      if (res.code === 200) {
        DeleteHumanBodySuccessArray.push(ID);
        console.log(`删除人体${ID}success`);
      }
    });
  };
  @action DeleteImageFun = async (src) => {
    // if (ID.indexOf('-') > -1) {
    const DeleteTheImageFunctionResult = await HumanBodyDatabaseManagementApi.DeleteImageVideoLibraryInsertFunction(src)
    if (DeleteTheImageFunctionResult.code === 200) {
      console.log(`删除图片${src}success`);
      DeletePictureSuccessArray.push(src);
    } else if (DeleteTheImageFunctionResult.code === 400) {
      console.log(`删除图片${src}fail,没有找到该图片`);
    } else {
      console.log(`删除图片${src}fail`);
    }
  };
  @action CreateHumanBodyLibraryFromImageClassMaterialFun = async (
    file,
    recognize_people_limition,
    step_frame_interval,
    last_time,
    token
  ) => {
    const formData = new FormData();
    formData.append("video-file", file);
    formData.append("limit", recognize_people_limition);
    formData.append("last", last_time);
    formData.append("interval", step_frame_interval);
    formData.append("libid", 'default');
    await HumanBodyDatabaseManagementApi.CreateHumanBodyLibraryFromImageClassMaterialFun(formData, token).then(res => {
      console.log(res);

      if (res.code === 200) {
        console.log("由图像类素材创建人体库成功,taskID为", res.data["task-id"]);
        runInAction(() => {
          this.upload_video_ok = true
        })
        message.info(
          "视频入库任务创建成功，预计需要" +
          Math.ceil(2000 / step_frame_interval) +
          "秒"
        )
      }
      else if (res.code === 500) {
        message.error('当前仍有任务在执行，请稍后重试')
      }
      else {
        message.error('文件大小不允许超过20Mb')
      }
    }, error => {
      console.log(error)
    });
  };
  @action human_feature_library_search_elements = async (vector, userName, token) => {
    let human_feature_library_search_element_results = {}
    let vecList = "base64://" + encodeURIComponent(vector);
    const formData = new FormData();
    formData.append("src", vecList);
    formData.append("top", 200);
    const res = await HumanBodyDatabaseManagementApi.human_body_search_element(formData, userName, token)
    console.log(res);
    if (res.data.length > 0) {
      //data中有数据直接取data的数据
      //处理data中返回的数据
      res.data.forEach(function (item) {
        item.score = String(item.score).substring(0, 5);
      });
      human_feature_library_search_element_results.information_array = res.data
    } else {
      let score_bigger_than_80 = [];
      for (let [index, each_item] of res.debug.entries()) {
        if (each_item.score >= 80) {
          score_bigger_than_80.push(each_item);
        }
      }
      //冒泡排序
      for (let i = 0; i < score_bigger_than_80.length - 1; i++) {
        for (let j = 0; j < score_bigger_than_80.length - 1 - i; j++) {
          if (
            score_bigger_than_80[j].score >
            score_bigger_than_80[j + 1].score
          ) {
            var temp = score_bigger_than_80[j].score;
            score_bigger_than_80[j].score =
              score_bigger_than_80[j + 1].score;
            score_bigger_than_80[j + 1].score = temp;
          }
        }
      }
      human_feature_library_search_element_results.information_array = score_bigger_than_80;
    }

    //这里已经获取到需要的数组，对数据进行五次方处理，返回大于70分的人

    console.log(human_feature_library_search_element_results)

    let new_human_feature_library_search_element_results = deep_copy(human_feature_library_search_element_results)





    for (let [index, item] of new_human_feature_library_search_element_results.information_array.entries()) {
      item.score = (Math.pow(item.score / 100, 5) * 100).toFixed(2)
    }
    console.log(new_human_feature_library_search_element_results)
    let i = new_human_feature_library_search_element_results.information_array.length



    while (i--) {
      if (new_human_feature_library_search_element_results.information_array[i].score < 80) {
        new_human_feature_library_search_element_results.information_array.splice(i, 1)
      }
    }

    // new_human_feature_library_search_element_results.information_array.splice(0, 1)


    console.log(new_human_feature_library_search_element_results)

    if (new_human_feature_library_search_element_results.information_array.length > 0) {
      new_human_feature_library_search_element_results.result = 'people_found'
    } else {
      new_human_feature_library_search_element_results.result = 'no_people_found'
    }

    return new_human_feature_library_search_element_results
  };

  @action get_current_user_task = async token => {
    let tast_id = undefined;
    await HumanBodyDatabaseManagementApi.get_current_user_task(token).then(res => {
      console.log(res);
      if (res.code === 200) {
        tast_id = res.data["task-id"];
        console.log("用户当前任务ID是", res.data["task-id"]);
      } else if (res.code === 404) {
        tast_id = null;
        console.log("用户当前无运行任务");
      } else {
        console.log("get_current_user_task出错了");
      }
    });
    return tast_id;
  };

  @action get_current_task_running_state = async (task_id, token) => {
    let task_running_condition = {};
    await HumanBodyDatabaseManagementApi.get_current_task_running_state(task_id, token).then(res => {
      console.log(res);
      if (res.code === 200) {
        if (res.data.finished) {
          task_running_condition.running_condition = "complete";
        } else {
          task_running_condition.running_condition = "incomplete";
          task_running_condition.rest_time =
            res.data.condition.last_for - res.data.last_for;
          task_running_condition.run_time = res.data.last_for;
          task_running_condition.interval = res.data.condition.interval
        }
      }
    });
    return task_running_condition;
  };
}

export default new HumanBodyManageStore();
